import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:wu_you/data/db/dao/transfer_user_dao.dart';
import 'package:wu_you/data/repository/auth_repository.dart';
import 'package:wu_you/data/repository/user_repository.dart';
import 'package:wu_you/l10n/messages.dart';
import 'package:wu_you/model/user/user_model.dart';
import 'package:wu_you/res/colors.dart';
import 'package:wu_you/state/bloc/http_bloc.dart';
import 'package:wu_you/state/bloc/user_bloc.dart';
import 'package:wu_you/utils/utils.dart';
import 'package:wu_you/widgets/bottom_picker.dart';
import 'package:wu_you/widgets/countdown_view.dart';
import 'package:wu_you/widgets/http_status_widget.dart';
import 'package:wu_you/utils/extension_utils.dart';

///转账
class TransferMoneyPage extends StatefulWidget{
  final String phone;
  TransferMoneyPage({Key key,this.phone}):super(key: key);
  @override
  TransferMoneyPageState createState() => TransferMoneyPageState();
}
class TransferMoneyPageState extends State<TransferMoneyPage>{
  final _formKey = GlobalKey<FormState>();
  var message;
  final _countdownKey = GlobalKey<CountdownViewState>();

  TextEditingController _controller = TextEditingController();
  FocusNode _focusNode = FocusNode();

  String _number2;
  String _smsCode;


  GlobalKey btnKey = GlobalKey();

  List<String> transferUserList = [];
  String categoryText = "消费积分";
  List<String> type = ['消费积分',"交易积分","无忧积分"];
  String trType = "1";
  @override
  void initState() {
    super.initState();
    // _getHistory();
  }

  ///获取转账历史
  _getHistory() async{
    transferUserList.clear();
    List<String> user = await TransferUserDao().getAll(widget.phone);
    transferUserList.addAll(user);
    setState(() {});
  }

  Widget buildAutoComplete() {
    return Autocomplete<String>(
      optionsBuilder: buildOptions,
      onSelected: (value){

      },
      optionsViewBuilder: _buildOptionsView,
      fieldViewBuilder: _buildFieldView,
      displayStringForOption: (user) => user,
    );
  }



  Future<Iterable<String>> buildOptions(TextEditingValue textEditingValue) async {
    // if (textEditingValue.text == '') {
    //   return const Iterable<String>.empty();
    // }
    return searchByArgs(textEditingValue.text);
  }
  Future<Iterable<String>> searchByArgs(String args) async {
    await Future.delayed(const Duration(milliseconds: 200));
    transferUserList.clear();
    List<String> user = await TransferUserDao().getAll(widget.phone);
    transferUserList.addAll(user);
    return transferUserList.where((user) => user.contains(args));
  }
  Widget _buildOptionsView(BuildContext context, AutocompleteOnSelected<String> onSelected, Iterable<String> options) {
    return Align(
      alignment: Alignment.topLeft,
      child: Padding(
        padding: EdgeInsets.zero,
        child: Material(
          child: ConstrainedBox(
            constraints: BoxConstraints(maxHeight: 150.0,maxWidth: 220),
            child: ListView.separated(
                padding: EdgeInsets.zero,
                itemBuilder: (context,index){
                  String option = options.elementAt(index);
                  return Container(
                    height: 45,
                    alignment: Alignment.centerLeft,
                    padding: EdgeInsets.only(left: 6,right: 6),
                    child: Text.rich(formSpan(option, _controller.text)),
                  ).addGesture(() {
                    onSelected.call(option);
                  });
                },
                separatorBuilder: (context,index){
                  return Divider();
                },
                itemCount: options .length
            )
          ),
        ),
      ),
    );
  }
  ///高亮某些文字
  final TextStyle lightTextStyle = const TextStyle(
    color: Colors.blue,
    fontWeight: FontWeight.bold,
  );
  InlineSpan formSpan(String src, String pattern) {
    List<TextSpan> span = [];
    List<String> parts = src.split(pattern);
    if (parts.length > 1) {
      for (int i = 0; i < parts.length; i++) {
        span.add(TextSpan(text: parts[i]));
        if (i != parts.length - 1) {
          span.add(TextSpan(text: pattern, style: lightTextStyle));
        }
      }
    } else {
      span.add(TextSpan(text: src));
    }
    return TextSpan(children: span,style: TextStyle(fontSize: 16,fontWeight: FontWeight.bold));
  }

  Widget _buildFieldView(
      BuildContext context,
      TextEditingController textEditingController,
      FocusNode focusNode,
      VoidCallback onFieldSubmitted) {
    _controller = textEditingController;
    _focusNode = focusNode;
    return SizedBox(
      height: 34,
      child: TextFormField(
        style: TextStyle(fontSize: 15,color: AppColors.textColor),
        maxLines: 1,
        textAlignVertical: TextAlignVertical.center,
        textInputAction: TextInputAction.next,
        keyboardType: TextInputType.text,
        autofocus: false,
        cursorColor: Theme.of(context).primaryColor,
        validator: (value) {
          return value.length == 0 ? '${message['text41']}' : null;
        },
        onFieldSubmitted: (String value) {
          onFieldSubmitted();
        },
        controller: textEditingController,
        focusNode: focusNode,
        textAlign: TextAlign.start,
        decoration: InputDecoration(
          suffixIcon: IconButton(
            splashColor: Colors.transparent,
            highlightColor: Colors.transparent,
            constraints: BoxConstraints.loose(Size(24, 24)),
            iconSize: 1,
            icon: Icon(Icons.clear,color: Colors.white,),
            onPressed: () {
            },
          ),
          border: UnderlineInputBorder(
            borderSide: BorderSide.none,
          ),
          errorMaxLines: 1,
          counterText: '',
          // contentPadding: EdgeInsets.only(left: 6),
          hintText: "${message['text41']}",
          hintStyle: TextStyle(fontSize: 15,color: AppColors.textHintColor),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    message = AppLocalizations.of(context);
    return MultiBlocProvider(
      providers: [
        BlocProvider.value(value: UserInfoBloc()),
      ],
      child: Scaffold(
          backgroundColor: Colors.white,
          appBar: AppBar(
            title: Text("${message['user20']}"),
          ),
          body: HttpWidget<UserInfoModel, UserInfoBloc>(
              create: (context) => BlocProvider.of<UserInfoBloc>(context)..add(HttpEvent()),
              child: (context, data) {
                return SingleChildScrollView(
                    child: Padding(
                      padding: EdgeInsets.only(left: 25,right: 25,top: 12,bottom: 20),
                      child: Form(
                        key: _formKey,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            ListTile(
                                onTap: (){
                                  closeKeyboard(context);
                                  showBottomSheetTool().showSingleRowPicker(
                                      context,
                                      data: type,
                                      clickCallBack: (index,item){
                                        print(item);
                                        setState(() {
                                          categoryText = item;
                                          if(item == "消费积分"){
                                            trType = "1";
                                          }else if(item == "交易积分"){
                                            trType = "2";
                                          }else if(item == "无忧积分"){
                                            trType = "3";
                                          }
                                        });
                                      });
                                },
                                leading: Text("转账类型",style: TextStyle(fontSize: 14, ),),
                                trailing: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    Text("$categoryText",style: TextStyle(color: AppColors.textHintColor),),
                                    Icon(Icons.arrow_forward_ios_outlined ,size: 20, color: AppColors.textHintColor,),
                                  ],
                                )
                            ),
                            Divider(
                              height: 2,
                              color: HexColor("#EAEAEA"),
                            ),
                            ListTile(
                              leading: Text("${message['text39']}",style: TextStyle(fontSize: 15)),
                              title: Text(_countText(data),style: TextStyle(fontSize: 15,color: AppColors.primaryColor)),
                            ),
                            Divider(
                              height: 2,
                              color: HexColor("#EAEAEA"),
                            ),
                            ListTile(
                              leading: Text("${message['text40']}",style: TextStyle(fontSize: 15, ),),
                              title: buildAutoComplete(),
                            ),

                            // ListTile(
                            //   leading: Text("${message['text40']}",style: TextStyle(fontSize: 15, ),),
                            //   title: TextFormField(
                            //     key: btnKey,
                            //     onTap: (){
                            //       if(transferUserList.length == 0){
                            //         return;
                            //       }
                            //       showPopupWindow(
                            //         context,
                            //         // childSize:Size(240, 200),
                            //         gravity: KumiPopupGravity.centerBottom,
                            //         curve: Curves.easeInCirc,
                            //         bgColor: Colors.grey.withOpacity(0.5),
                            //         clickOutDismiss: true,
                            //         clickBackDismiss: true,
                            //         customAnimation: false,
                            //         customPop: false,
                            //         customPage: false,
                            //         targetRenderBox: (btnKey.currentContext.findRenderObject() as RenderBox),
                            //         needSafeDisplay: true,
                            //         underStatusBar: false,
                            //         underAppBar: false,
                            //         duration: Duration(milliseconds: 300),
                            //         onClickOut: (pop) {
                            //           print("onClickOut");
                            //         },
                            //         onClickBack: (pop) {
                            //           print("onClickBack");
                            //         },
                            //         childFun: (pop) {
                            //           return StatefulBuilder(
                            //               key: GlobalKey(),
                            //               builder: (popContext, popState) {
                            //                 return Container(
                            //                     padding: EdgeInsets.only(left: 10,right: 10),
                            //                     height: transferUserList.length > 5 ? 200 : transferUserList.length * 45.0,
                            //                     width: 180,
                            //                     color: HexColor("#F6F6F6"),
                            //                     alignment: Alignment.center,
                            //                     child: ListView.separated(
                            //                         padding: EdgeInsets.zero,
                            //                         itemBuilder: (context,index){
                            //                           String user = transferUserList[index];
                            //                           return Container(
                            //                             height: 45,
                            //                             alignment: Alignment.center,
                            //                             child: Row(
                            //                               mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            //                               children: [
                            //                                 Text("${user.length > 11 ? "${user.substring(0,11)}..." : user}",style: TextStyle(color: Colors.black,fontSize: 15),),
                            //                                 Icon(Icons.clear,color: AppColors.textHintColor,).addGesture(() async{
                            //                                   await TransferUserDao().delete(widget.phone,user);
                            //                                   _getHistory();
                            //                                   pop.dismiss(context);
                            //                                 })
                            //                               ],
                            //                             ),
                            //                           ).addGesture(() {
                            //                             popState(() {
                            //                               _controller.text = "$user";
                            //                             });
                            //                             pop.dismiss(context);
                            //                           });
                            //
                            //                           return Row(
                            //                             mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            //                             children: [
                            //                               Text("$user",style: TextStyle(color: Colors.black,fontSize: 15),),
                            //                               Icon(Icons.clear,color: AppColors.textHintColor,)
                            //                             ],
                            //                           ).addGesture(() {
                            //                             popState(() {
                            //                               _controller.text = "$user";
                            //                             });
                            //                             pop.dismiss(context);
                            //                           });
                            //                         },
                            //                         separatorBuilder: (context,index){
                            //                           return Divider();
                            //                         },
                            //                         itemCount: transferUserList.length
                            //                     )
                            //                 );
                            //               });
                            //         },
                            //       );
                            //     },
                            //     style: TextStyle(fontSize: 15,color: AppColors.textColor),
                            //     maxLines: 1,
                            //     textAlignVertical: TextAlignVertical.center,
                            //     textInputAction: TextInputAction.next,
                            //     keyboardType: TextInputType.text,
                            //     autofocus: false,
                            //     cursorColor: Theme.of(context).primaryColor,
                            //     validator: (value) {
                            //       return value.length == 0 ? '${message['text41']}' : null;
                            //     },
                            //     // onChanged: (value){
                            //     //   _number1 = value;
                            //     // },
                            //     // onSaved: (value) {
                            //     //   _number1 = value;
                            //     // },
                            //     controller: _controller,
                            //     textAlign: TextAlign.start,
                            //     decoration: InputDecoration(
                            //       suffixIcon: IconButton(
                            //         splashColor: Colors.transparent,
                            //         highlightColor: Colors.transparent,
                            //         constraints: BoxConstraints.loose(Size(24, 24)),
                            //         iconSize: 1,
                            //         icon: Icon(Icons.clear,color: Colors.white,),
                            //         onPressed: () {
                            //         },
                            //       ),
                            //       border: UnderlineInputBorder(
                            //         borderSide: BorderSide.none,
                            //       ),
                            //       errorMaxLines: 1,
                            //       counterText: '',
                            //       // contentPadding: EdgeInsets.only(left: 6),
                            //       hintText: "${message['text41']}",
                            //       hintStyle: TextStyle(fontSize: 15,color: AppColors.textHintColor),
                            //     ),
                            //   ),
                            // ),
                            Divider(
                              height: 2,
                              color: HexColor("#EAEAEA"),
                            ),

                            ListTile(
                              leading: Text("${message['text42']}",style: TextStyle(fontSize: 15, ),),
                              title:  TextFormField(
                                style: TextStyle(fontSize: 15,color: AppColors.textColor),
                                maxLines: 1,
                                textAlignVertical: TextAlignVertical.center,
                                textInputAction: TextInputAction.next,
                                keyboardType: TextInputType.text,
                                autofocus: false,
                                cursorColor: Theme.of(context).primaryColor,
                                validator: (value) {
                                  return value.length == 0 ? '${message['text43']}' : null;
                                },
                                onChanged: (value){
                                  _number2 = value;
                                },
                                onSaved: (value) {
                                  _number2 = value;
                                },
                                textAlign: TextAlign.start,
                                decoration: InputDecoration(
                                  suffixIcon: IconButton(
                                    splashColor: Colors.transparent,
                                    highlightColor: Colors.transparent,
                                    constraints: BoxConstraints.loose(Size(24, 24)),
                                    iconSize: 1,
                                    icon: Icon(Icons.clear,color: Colors.white,),
                                    onPressed: () {
                                    },
                                  ),
                                  border: UnderlineInputBorder(
                                    borderSide: BorderSide.none,
                                  ),
                                  errorMaxLines: 1,
                                  counterText: '',
                                  // contentPadding: EdgeInsets.only(left: 1),
                                  hintText: "${message['text43']}",
                                  hintStyle: TextStyle(fontSize: 15,color: AppColors.textHintColor),
                                ),
                              ),
                            ),
                            Divider(
                              height: 2,
                              color: HexColor("#EAEAEA"),
                            ),
                            ListTile(
                              leading: Padding(
                                padding: EdgeInsets.only(top: 5),
                                child: Text("${message['text13']}",style: TextStyle(fontSize: 15, ),),
                              ),
                              title: TextFormField(
                                style: TextStyle(color: Colors.black,fontSize: 15),
                                maxLines: 1,
                                textAlignVertical: TextAlignVertical.center,
                                textInputAction: TextInputAction.done,
                                // maxLength: 4,
                                keyboardType: TextInputType.numberWithOptions(),
                                autofocus: false,
                                obscureText: false,
                                cursorColor: Theme.of(context).primaryColor,
                                validator: (value) {
                                  return value.length == 0 ? '${message['enterCode']}' : null;
                                },
                                onSaved: (value) {
                                  _smsCode = value;
                                },
                                decoration: InputDecoration(
                                  fillColor: Colors.white,
                                  filled: true,
                                  prefixIconConstraints: BoxConstraints.loose(Size(64, 50)),
                                  suffixIconConstraints: BoxConstraints.loose(Size(100, 56)),
                                  suffixIcon: CountdownView(
                                    key: _countdownKey,
                                    hint: Text(
                                      "${message['getCode']}",
                                      style: TextStyle(color: AppColors.primaryColor, fontSize: 14),
                                    ),
                                    onPressed: () {
                                      closeKeyboard(context);
                                      _onGetCode(data.phone);
                                    },
                                  ),
                                  border: UnderlineInputBorder(
                                    borderSide: BorderSide.none,
                                    borderRadius: const BorderRadius.all(Radius.circular(24)),
                                  ),
                                  errorMaxLines: 1,
                                  counterText: '',
                                  contentPadding: EdgeInsets.only(left: 15, right: 2),
                                  hintText: "${message['enterCode']}",
                                  hintStyle: TextStyle(fontSize: 15,color: AppColors.textHintColor),
                                ),
                              ),
                            ),
                            Divider(
                              height: 2,
                              color: HexColor("#EAEAEA"),
                            ),

                            Offstage(
                              offstage: trType == "1" ? false : true,
                              child: Padding(padding: EdgeInsets.only(left: 18,top: 18),
                                child: Text("提示:手续费${double.parse("${data.transferaccounts_fee}") * 100}%",style: TextStyle(fontSize: 13,color: AppColors.primaryColor),),
                              ),
                            ),

                            SizedBox(height: 20,),

                            SizedBox(
                              width: double.infinity,
                              height: 42,
                              child: ElevatedButton(
                                child: Text("${message['cp6']}"),
                                style: ButtonStyle(
                                  backgroundColor: MaterialStateProperty.all(AppColors.primaryColor),
                                  shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(8))),//圆角弧度
                                ),
                                onPressed: _onSubmit,
                              ),
                            ),
                          ],
                        ),
                      ),
                    )
                );
              }
          )
      ),
    );
  }

  String _countText(UserInfoModel data){
    if(trType == "1"){
      return  "${data.money}";
    }else if(trType == "2"){
      return "${data.myr}";
    }else if(trType == "3"){
      return "${data.usdt}";
    }else{
      return "";
    }
  }

  void _onGetCode(String phone){
    _countdownKey.currentState.state = CountdownState.loading;
    LoadingApi.func(AuthRepository().getSmsCode(9,phone: phone), context,showLoading: false,complete: (value){
      _countdownKey.currentState.state = CountdownState.countdown;
      ToastUtils.show("$value", context);
    },error: (error){
      _countdownKey.currentState.state = CountdownState.init;
      ToastUtils.show("$error", context);
    });
  }
  void _onSubmit(){
    var _state = _formKey.currentState;
    _state.save();
    if (!_state.validate()) {
      return;
    }
    closeKeyboard(context);
    LoadingApi.func(UserRepository().transferMoney(_controller.text, _number2,_smsCode,trType), context,complete: (v) async{
      ToastUtils.show("$v", context);
      ///保存转账对象账号
      await TransferUserDao().insert(widget.phone, _controller.text);
      Future.delayed(const Duration(milliseconds: 800), () {
        Navigator.of(context).pop(1);
      });
    },error: (e){
      ToastUtils.show("$e", context);
    });
  }
}







///兑换
class ExchangeMoneyPage extends StatefulWidget{
  final String phone;
  ExchangeMoneyPage({Key key,this.phone}):super(key: key);
  @override
  ExchangeMoneyPageState createState() => ExchangeMoneyPageState();
}
class ExchangeMoneyPageState extends State<ExchangeMoneyPage>{
  final _formKey = GlobalKey<FormState>();

  String _number;


  GlobalKey btnKey = GlobalKey();

  List<String> transferUserList = [];
  @override
  void initState() {
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return MultiBlocProvider(
      providers: [
        BlocProvider.value(value: UserInfoBloc()),
      ],
      child: Scaffold(
          backgroundColor: Colors.white,
          appBar: AppBar(
            title: Text("消费积分兑换无忧积分"),
          ),
          body: HttpWidget<UserInfoModel, UserInfoBloc>(
              create: (context) => BlocProvider.of<UserInfoBloc>(context)..add(HttpEvent()),
              child: (context, data) {
                return SingleChildScrollView(
                    child: Padding(
                      padding: EdgeInsets.only(left: 25,right: 25,top: 12,bottom: 20),
                      child: Form(
                        key: _formKey,
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            ListTile(
                              leading: Text("余额",style: TextStyle(fontSize: 15)),
                              title: Text("${data.money}",style: TextStyle(fontSize: 15,color: AppColors.primaryColor)),
                            ),
                            Divider(
                              height: 2,
                              color: HexColor("#EAEAEA"),
                            ),
                            ListTile(
                              leading: Text("兑换数量",style: TextStyle(fontSize: 15, ),),
                              title:  TextFormField(
                                style: TextStyle(fontSize: 15,color: AppColors.textColor),
                                maxLines: 1,
                                textAlignVertical: TextAlignVertical.center,
                                textInputAction: TextInputAction.next,
                                keyboardType: TextInputType.text,
                                autofocus: false,
                                cursorColor: Theme.of(context).primaryColor,
                                validator: (value) {
                                  return value.length == 0 ? '请输入兑换数量' : null;
                                },
                                onChanged: (value){
                                  _number = value;
                                },
                                onSaved: (value) {
                                  _number = value;
                                },
                                textAlign: TextAlign.start,
                                decoration: InputDecoration(
                                  suffixIcon: IconButton(
                                    splashColor: Colors.transparent,
                                    highlightColor: Colors.transparent,
                                    constraints: BoxConstraints.loose(Size(24, 24)),
                                    iconSize: 1,
                                    icon: Icon(Icons.clear,color: Colors.white,),
                                    onPressed: () {
                                    },
                                  ),
                                  border: UnderlineInputBorder(
                                    borderSide: BorderSide.none,
                                  ),
                                  errorMaxLines: 1,
                                  counterText: '',
                                  // contentPadding: EdgeInsets.only(left: 1),
                                  hintText: "请输入兑换数量",
                                  hintStyle: TextStyle(fontSize: 15,color: AppColors.textHintColor),
                                ),
                              ),
                            ),
                            Divider(
                              height: 2,
                              color: HexColor("#EAEAEA"),
                            ),

                            Offstage(
                              offstage: double.parse("${data.exchange_fee}") > 0 ? false : true,
                              child: Padding(padding: EdgeInsets.only(left: 18,top: 18),
                                child: Text("提示:手续费${double.parse("${data.exchange_fee}") * 100}%",style: TextStyle(fontSize: 13,color: AppColors.primaryColor),),
                              ),
                            ),

                            SizedBox(height: 20,),

                            SizedBox(
                              width: double.infinity,
                              height: 42,
                              child: ElevatedButton(
                                child: Text("确定"),
                                style: ButtonStyle(
                                  backgroundColor: MaterialStateProperty.all(AppColors.primaryColor),
                                  shape: MaterialStateProperty.all(RoundedRectangleBorder(borderRadius: BorderRadius.circular(8))),//圆角弧度
                                ),
                                onPressed: _onSubmit,
                              ),
                            ),
                          ],
                        ),
                      ),
                    )
                );
              }
          )
      ),
    );
  }
  void _onSubmit(){
    var _state = _formKey.currentState;
    _state.save();
    if (!_state.validate()) {
      return;
    }
    closeKeyboard(context);
    LoadingApi.func(UserRepository().exchangeMoney(_number), context,complete: (v) async{
      ToastUtils.show("$v", context);
      Future.delayed(const Duration(milliseconds: 800), () {
        Navigator.of(context).pop(1);
      });
    },error: (e){
      ToastUtils.show("$e", context);
    });
  }
}